package zhh.tangbao.commodity.manager;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import zhh.tangbao.commodity.dao.CommodityOrderDao;
import zhh.tangbao.commodity.constant.OrderStatus;
import zhh.tangbao.commodity.manager.expire.OrderExpireTimer;
import zhh.tangbao.system.config.OrderTimerConfig;

import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

/**
 * <p>
 *     订单过期期限管理
 * </p>
 * @author 粥灰灰
 * <p>2023/3/21</p>
 */

@Component
public class OrderManager {

    @Autowired
    private CommodityOrderDao orderDao;


    @Autowired
    private OrderTimerConfig orderTimerConfig;

    private Map<String, OrderExpireTimer> orderExpireMap = Maps.newConcurrentMap();

    public void addOrderExpire(String orderId) {
        OrderExpireTimer t = new OrderExpireTimer(orderTimerConfig.getExpire());
        t.schedule(new TimerTask() {
            @Override
            public void run() {
                // 更新状态
                orderDao.cancelOrderIfNotPayment(orderId, OrderStatus.CANCEL.getCode());
                // 然后移除Timer
                orderExpireMap.remove(orderId);
            }
        }, orderTimerConfig.getExpire());
        orderExpireMap.put(orderId, t);
    }

    public void cancelExpireTimer(String orderId) {
        // 更新状态
        OrderExpireTimer orderExpireTimer = orderExpireMap.get(orderId);
        if (null != orderExpireTimer) {
            orderExpireTimer.cancel();
        }
        // 然后移除Timer
        orderExpireMap.remove(orderId);
    }

    public Long getExpireTime(String orderId) {
        OrderExpireTimer orderExpireTimer = orderExpireMap.get(orderId);
        if (null == orderExpireTimer) {
            return 0L;
        }
        return orderExpireTimer.getMaturityTime();
    }
}
